from cProfile import run
import time,threading
from tokenize import blank_re


balance=0
lock=threading.Lock()
def change_it(n):
    #先存后取，结果应是0
    global balance
    balance=balance+n
    balance=balance-n
def run_thread(n):
    for i in range(2000000):
        #先获取锁
        lock.acquire()
        try:
            #安心修改余额
            change_it(n)
        finally:
            #改完一定要释放锁
            lock.release()
t1=threading.Thread(target=run_thread,args=(5,))
t2=threading.Thread(target=run_thread,args=(8,))
t1.start()
t2.start()
t1.join()
t2.join()
print('balance=',balance)

def loop():
    print('thread %s is running...'%threading.current_thread().name)
    n=0
    while n<5:
        n=n+1
        print('thread %s>>>%s'%(threading.current_thread(),n))
        time.sleep(1)
    print('thread %s ended.'%threading.current_thread().name)
#current_thread()函数，它永远返回当前线程的实例。
print('thread %s is running...'%threading.current_thread().name)
t=threading.Thread(target=loop,name='LoopThread')
t.start()
t.join()
print('thread %s ended.'%threading.current_thread().name)